package com.huawei123.hasee.cniao5store.mvp.view.acyivity;

import android.content.Intent;
import android.os.Environment;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.format.Formatter;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.huawei123.hasee.cniao5store.R;
import com.huawei123.hasee.cniao5store.adapter.AppDetailPagerAdapter;
import com.huawei123.hasee.cniao5store.base.BaseMvpActivity;
import com.huawei123.hasee.cniao5store.bean.AppDetailBean;
import com.huawei123.hasee.cniao5store.mvp.presenter.impl.AppDetailPresenterImpl;
import com.huawei123.hasee.cniao5store.mvp.view.fragment.AppCommentFragment;
import com.huawei123.hasee.cniao5store.mvp.view.fragment.AppIntroductionFragment;
import com.huawei123.hasee.cniao5store.mvp.view.fragment.AppRecommendFragment;
import com.huawei123.hasee.cniao5store.mvp.view.view.AppDetailActivityView;
import com.huawei123.hasee.cniao5store.utils.AppInfoUtils;
import com.huawei123.hasee.cniao5store.utils.UIUtils;
import com.huawei123.hasee.cniao5store.view.widget.DetailShareButton;
import com.huawei123.hasee.cniao5store.view.widget.DownloadProgressButton;
import com.huawei123.hasee.cniao5store.view.widget.SubTabNavigator;
import com.zhxu.library.download.DownInfo;
import com.zhxu.library.download.DownState;
import com.zhxu.library.download.HttpDownManager;
import com.zhxu.library.utils.DbDownUtil;


import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;


/**
 * 下载应用详情界面
 */
public class AppDetailActivity extends BaseMvpActivity<AppDetailPresenterImpl> implements AppDetailActivityView,
        HttpDownManager.DownloadObserver {
    @BindView(R.id.title_text)
    TextView title_text;
    //    @BindView(R.id.iv_search)
    //    ImageView iv_search;

    @BindView(R.id.iv_back)
    ImageView iv_back;


    @BindView(R.id.detail_head_app_icon_imageview)
    ImageView detail_app_icon;
    @BindView(R.id.detail_head_app_name_textview)
    TextView detail_app_name;
    @BindView(R.id.detail_head_download_count_textview)
    TextView detail_app_download_count;
    @BindView(R.id.detail_head_app_stars_ratingbar)
    RatingBar detail_app_stars;
    @BindView(R.id.detail_head_label_layout_linearlayout)
    RelativeLayout detail_head_label_layout;
    @BindView(R.id.detail_head_label_icon_layout_linearlayout)
    LinearLayout detail_head_label_icon_layout;
    @BindView(R.id.detail_head_lable_folding_textview)
    TextView detail_head_lable_folding;
    @BindView(R.id.detail_head_safe_icon_container_linearlayout)
    LinearLayout detail_head_safe_icon_container;
    @BindView(R.id.detail_head_safe_icon_layout_linearlayout)
    LinearLayout detail_head_safe_icon_layout;
    @BindView(R.id.subTab)
    SubTabNavigator subTabNavigator;
    @BindView(R.id.vp)
    ViewPager mViewPager;
    @BindView(R.id.appdetail_head)
    LinearLayout appdetail_head;
    @BindView(R.id.detail_download_button)
    DownloadProgressButton detail_download_button;
    @BindView(R.id.detail_download_share_button)
    DetailShareButton detail_download_share_button;
    @BindView(R.id.detail_download_comment_button_linearlayout)
    LinearLayout detail_download_comment_button_linearlayout;

    protected boolean expand = false;
    @Inject
    public AppDetailPresenterImpl appDetailPresenter;
    private AppDetailBean subTab;
    private AppDetailBean appDetailBean;
    private List<Fragment> fragments;
    private String packageName;
    private HttpDownManager httpManager;
    private File outputFile;
    private DbDownUtil dbDownUtil;
    private DownInfo downInfo;

    @Override
    protected AppDetailPresenterImpl initPresenterInjector() {
        mActivityComponent.inject(this);
        return appDetailPresenter;
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_app_detail);
    }

    @Override
    protected void initView() {
        //设置沉浸式状态栏
        setStatusBar();
        iv_back.setVisibility(View.VISIBLE);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //设置沉浸式状态栏背景
        if (mRL_bar_layout != null) {
            mRL_bar_layout.setBackgroundResource(R.color.black_alpha_5);
        }
        title_text.setText(getResources().getString(R.string.title_activity_app_detail));
    }

    @Override
    protected void initData() {
        super.initData();
        httpManager = HttpDownManager.getInstance();
        httpManager.registerObserver(this);
        //判定下载任务文件是否已存在，不存在新建下载文件储存路径
        Intent intent = getIntent();
        packageName = intent.getStringExtra("packageName");
        dbDownUtil = DbDownUtil.getInstance();
        downInfo = dbDownUtil.queryDownBy(packageName.hashCode());
        if (downInfo == null) {
            outputFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + packageName
                    + ".apk");
        }
        //开启界面逻辑
        appDetailPresenter.getAppDetailData(this, packageName);
    }

    @Override
    public void onAppDetailDataSuccess(AppDetailBean appDetailBean) {
        this.appDetailBean = appDetailBean;
        setDetailHead();
        setDetailLabel();
        setSafeLabel();
        setSubTab();
        setDetailDown();
        //点击检测条目弹出检测内容
        detail_head_label_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (expand) {

                    detail_head_safe_icon_layout.setVisibility(View.GONE);
                    expand = false;
                } else {
                    detail_head_safe_icon_layout.setVisibility(View.VISIBLE);
                    expand = true;
                }
            }
        });
    }

    /**
     * 顶部数据加载
     */
    private void setDetailHead() {
        Glide.with(UIUtils.getContext()).load(appDetailBean.getIcoUrl()).into(detail_app_icon);
        detail_app_name.setText(appDetailBean.getName());
        detail_app_download_count.setText(appDetailBean.getIntro());
        detail_app_stars.setRating(Float.parseFloat(appDetailBean.getStars()));
    }

    /**
     * 添加检测标签
     */
    public void setDetailLabel() {
        for (AppDetailBean.LabelName lableNameBean : appDetailBean.getLabelNameList()) {
            View labelView = UIUtils.inflate(R.layout.appdetail_item_head_label_item);
            TextView mTV_appdetail_head_label_textview = (TextView) labelView.findViewById(R.id
                    .appdetail_head_label_textview);
            mTV_appdetail_head_label_textview.setText(lableNameBean.getName());
            if (lableNameBean.getType() == 1) {
                mTV_appdetail_head_label_textview.setTextColor(getResources().getColor(R.color.app_not_safe_textcolor));
            }
            detail_head_label_icon_layout.addView(labelView);
        }
    }

    /**
     * 添加检测条目
     */
    private void setSafeLabel() {
        for (AppDetailBean.SafeLabel safeLabelsBean : appDetailBean.getSafeLabelList()) {
            View safeLabelView = UIUtils.inflate(R.layout.appdetail_item_head_safe_item);
            TextView safe_checker = (TextView) safeLabelView.findViewById(R.id.safe_checker_textview);
            TextView safe_checker_label = (TextView) safeLabelView.findViewById(R.id.safe_checker_label);
            ImageView detail_head_app_icon = (ImageView) safeLabelView.findViewById(R.id.detail_head_app_icon_imageview);
            TextView detail_safe_desc_textview = (TextView) safeLabelView.findViewById(R.id.mTV_detail_safe_desc_textview);

            safe_checker.setText(safeLabelsBean.getDetectorName());
            safe_checker_label.setText(safeLabelsBean.getDetectorDesc());
            Glide.with(UIUtils.getContext()).load(safeLabelsBean.getUrl()).into(detail_head_app_icon);
            detail_safe_desc_textview.setText(safeLabelsBean.getName());

            detail_head_safe_icon_container.addView(safeLabelView);
        }
    }

    /**
     * 添加绑定介绍，评论，推荐切换控件
     */
    public void setSubTab() {
        //填充介绍评论推荐三切换按钮的内容值
        subTabNavigator.setLeftText(appDetailBean.getTabInfoList().get(0));
        subTabNavigator.setNoneText(appDetailBean.getTabInfoList().get(1));
        subTabNavigator.setRightText(appDetailBean.getTabInfoList().get(2));
        //设置切换Fragment到ViewPager中
        fragments = new ArrayList<>();
        AppDetailPagerAdapter appDetailPagerAdapter = new AppDetailPagerAdapter(getSupportFragmentManager());
        AppIntroductionFragment appIntroductionFragment = new AppIntroductionFragment();
        AppCommentFragment appCommentFragment = new AppCommentFragment();
        AppRecommendFragment appRecommendFragment = new AppRecommendFragment();
        fragments.add(appIntroductionFragment);
        fragments.add(appCommentFragment);
        fragments.add(appRecommendFragment);
        appDetailPagerAdapter.setFragments(fragments);
        mViewPager.setAdapter(appDetailPagerAdapter);
        //viewPager与自定义三按钮控件相互关联绑定
        mViewPager.setOnPageChangeListener(subTabNavigator);
        subTabNavigator.setViewPager(mViewPager);

    }

    /**
     * 设置下载按钮逻辑
     */
    private void setDetailDown() {
        //设置下载按钮初始化状态
        if (downInfo == null) {
            detail_download_button.setStartText("安装" + Formatter.formatFileSize(UIUtils.getContext(), Long.parseLong
                    (appDetailBean.getSize())));
        } else {
            if (downInfo.getState() == DownState.START) {
                detail_download_button.setState(DownloadProgressButton.STATUS_PROGRESS_BAR_DOWNLOADING);
                httpManager.startDown(downInfo);
            } else if (downInfo.getState() == DownState.PAUSE) {
                detail_download_button.setState(DownloadProgressButton.STATUS_PROGRESS_BAR_PAUSE);
            } else if (downInfo.getState() == DownState.FINISH) {
                detail_download_button.setState(DownloadProgressButton.STATUS_PROGRESS_BAR_BEGIN);
            }
            //放入当前进度值
            detail_download_button.setProgress((int) (100 * downInfo.getReadLength() / downInfo.getCountLength()));
        }

        detail_download_button.setStateChangeListener(new DownloadProgressButton.StateChangeListener() {
            @Override
            public void onPauseTask() {
                httpManager.pause(downInfo);
            }

            @Override
            public void onFinishTask() {
                //下载结束，暂停三秒进行安装APP，
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        SystemClock.sleep(3000);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                AppInfoUtils.install(downInfo.getSavePath());
                                if (dbDownUtil != null && downInfo != null) {
                                    dbDownUtil.update(downInfo);
                                }
                            }
                        });
                    }
                }).start();

            }

            @Override
            public void onLoadingTask() {
                //点击
                detail_download_button.setMax(100);
                if (downInfo == null) {
                    downInfo = new DownInfo(appDetailBean.getDownloadUrl());
                    downInfo.setId((long) packageName.hashCode());
                    downInfo.setState(DownState.START);
                    downInfo.setSavePath(outputFile.getAbsolutePath());
                    dbDownUtil.save(downInfo);
                }
                //状态如果不是下载结束就继续下载
                if (downInfo.getState() != DownState.FINISH) {
                    httpManager.startDown(downInfo);
                }
            }
        });
    }

    public String getAppPackageName(){
        return packageName ;
    }
    @Override
    public void onDownloadStateChanged(DownInfo info) {

    }

    @Override
    public void onDownloadProgressed(DownInfo info) {
        if (downInfo != null && info.getId() == downInfo.getId()) {
            detail_download_button.setProgress((int) (100 * info.getReadLength() / info.getCountLength()));
        }
    }

    @Override
    public void onAppDetailDataError(String msg) {
        setContentView(R.layout.loading_page_empty);
    }


}
